import path from 'path'
import fs from 'fs'
import compressing from 'compressing'

/** 获取扩展名 */
export function getExtName(filename: string) {
  return path.extname(filename)?.replace('.', '')
}

/** 获取文件名称，无扩展名 */
export function getBaseName(filename: string) {
  let basename = path.basename(filename) || ''
  let extname = path.extname(filename) || ''
  return basename.replace(extname, '')
}

/** 获取对象的字段值 */
export function getObjectValue<T extends object, K extends keyof T>(obj: T, key: K) {
  return obj[key]
}

/**
 * 删除指定文件夹下的所有文件
 * 
 * @param path 文件夹路径
 */
export function deleteDir(path: string) {
  return new Promise<void>((resolve, reject) => {
    let files = []
    if (fs.existsSync(path)) {
      files = fs.readdirSync(path)
      for (let file of files) {
        let curPath = path + "/" + file
        if (fs.statSync(curPath).isDirectory()) {
          deleteDir(curPath)
        } else {
          fs.unlinkSync(curPath)
        }
      }
      fs.rmdirSync(path)
    }
    resolve()
  })
}

/** 
 * 获取指定范围内的随机数
 * 
 * 返回 [x, y] 范围内的随机数
 */
export function getRamdomNumberByRange(x: number, y: number) {
  return Math.round(Math.random() * (y - x) + x)
}

/** 
 * 压缩文件夹
 */
export function compressDir(sourceDirPath: string, targetFilePath: string): Promise<void> {
  return compressing.zip.compressDir(sourceDirPath, targetFilePath)
}